package com.ktg.mes.pro.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.dv.domain.DvMachinery;
import com.ktg.mes.dv.service.IDvMachineryService;
import com.ktg.mes.pro.domain.ProRouteProcess;
import com.ktg.mes.pro.domain.ProTask;
import com.ktg.mes.pro.service.IProRouteProcessService;
import com.ktg.mes.pro.service.IProTaskService;
import com.ktg.mes.rec.domain.RecDispersedRecord;
import com.ktg.mes.rec.domain.RecLnspectionRecord;
import com.ktg.mes.rec.service.IRecLnspectionRecordService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.pro.domain.ProTaskDeviceProcess;
import com.ktg.mes.pro.service.IProTaskDeviceProcessService;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * 创建生产关联（排产任务，生产设备，工序）Controller
 *
 * @author byteco
 * @date 2022-11-23
 */
@RestController
@RequestMapping("/pro/proTaskDeviceProcess")
public class ProTaskDeviceProcessController extends BaseController
{


    @Autowired
    private IProTaskDeviceProcessService proTaskDeviceProcessService;

    @Autowired
    private IProTaskService proTaskService;

    @Autowired
    private IDvMachineryService dvMachineryService;

    @Autowired
    private IProRouteProcessService proRouteProcessService;

    @Autowired
    private IRecLnspectionRecordService recLnspectionRecordService;


    /**
     * 查询创建生产关联（排产任务，生产设备，工序）列表
     */
    @PreAuthorize("@ss.hasPermi('pro:proTaskDeviceProcess:list')")
    @GetMapping("/list")
    public Result<IPage<ProTaskDeviceProcess>> list(ProTaskDeviceProcess proTaskDeviceProcess,
                                            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                            HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询创建生产关联（排产任务，生产设备，工序）列表",req,null);
        try {
            Page<ProTaskDeviceProcess> page = new Page<ProTaskDeviceProcess>(pageNo, pageSize);
            IPage<ProTaskDeviceProcess> pageList = proTaskDeviceProcessService.queryPageList(proTaskDeviceProcess,page);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 导出创建生产关联（排产任务，生产设备，工序）列表
     */
    @PreAuthorize("@ss.hasPermi('pro:proTaskDeviceProcess:export')")
    @Log(title = "创建生产关联（排产任务，生产设备，工序）", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProTaskDeviceProcess proTaskDeviceProcess,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出创建生产关联（排产任务，生产设备，工序）列表",req,proTaskDeviceProcess);
        try {
            List<ProTaskDeviceProcess> list = proTaskDeviceProcessService.queryList(proTaskDeviceProcess);
            ExcelUtil<ProTaskDeviceProcess> util = new ExcelUtil<ProTaskDeviceProcess>(ProTaskDeviceProcess.class);
            util.exportExcel(response, list, "创建生产关联（排产任务，生产设备，工序）数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取创建生产关联（排产任务，生产设备，工序）详细信息
     */
    @PreAuthorize("@ss.hasPermi('pro:proTaskDeviceProcess:query')")
    @GetMapping(value = "/{recorid}")
    public Result<ProTaskDeviceProcess> getInfo(@PathVariable("recorid") Long recorid,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取创建生产关联（排产任务，生产设备，工序）详细信息",req,null);
        try {
            return apiLog.ok(proTaskDeviceProcessService.getInfo(recorid));
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增创建生产关联（排产任务，生产设备，工序）
     */
    @PreAuthorize("@ss.hasPermi('pro:proTaskDeviceProcess:add')")
    @Log(title = "创建生产关联（排产任务，生产设备，工序）", businessType = BusinessType.INSERT)
    @PostMapping(value = "add")
    public Result<String> add(@RequestBody ProTaskDeviceProcess proTaskDeviceProcess,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增创建生产关联（排产任务，生产设备，工序）",req,proTaskDeviceProcess);
        try {
            String error = proTaskService.updateFromProTaskDeviceProcess(proTaskDeviceProcess);
            if (error != null){
                return apiLog.fail(error);
            }

            //获取设备
            DvMachinery dvMachinery = dvMachineryService.getById(proTaskDeviceProcess.getDeviceId());
            if (dvMachinery == null){
                return apiLog.fail("设备不存在");
            }

            //获取设备
            ProRouteProcess process = proRouteProcessService.getById(proTaskDeviceProcess.getProcessId());
            if (process == null){
                return apiLog.fail("工艺项不存在");
            }

            //获取任务
            ProTask task = proTaskService.getById(proTaskDeviceProcess.getTaskId());
            if (task == null){
                return apiLog.fail("任务不存在");
            }

            proTaskDeviceProcess.setProcessName(process.getProcessName()+":"+process.getGroupNum()+":"+proTaskDeviceProcess.getWorkType());
            proTaskDeviceProcess.setParamJson(process.getParamJson());

            proTaskDeviceProcess.setTaskName(task.getTaskName());
            proTaskDeviceProcess.setBatchNo(task.getBatchNo());

            proTaskDeviceProcess.setDeviceName(dvMachinery.getMachineryName());
            proTaskDeviceProcess.setWattHourMeter(dvMachinery.getWattHourMeter());
            proTaskDeviceProcess.setThermometer(dvMachinery.getThermometer());
            proTaskDeviceProcess.setWarmHumid(dvMachinery.getWarmHumid());

            proTaskDeviceProcessService.insert(proTaskDeviceProcess);
            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * PDA 使用 新增创建生产关联（排产任务，生产设备，工序）
     */
    @Log(title = "PDA 创建生产关联（排产任务，生产设备，工序）", businessType = BusinessType.INSERT)
    @GetMapping(value = "padAdd")
    public Result<String> padAdd(@RequestParam(value = "batchNo",required = true) String batchNo, //批次
                                 @RequestParam(value = "processId",required = true) String processId, //工序id
                                 @RequestParam(value = "deviceCode",required = false) String deviceCode, //设备号
                                 @RequestParam(value = "type",required = false) String type,
                                 HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("PDA 新增创建生产关联（排产任务，生产设备，工序）",req,batchNo+":"+processId+":"+deviceCode);
        try {
            Object obj = proTaskDeviceProcessService.initOrFind(batchNo,Long.valueOf(processId),deviceCode,type);
            ProTaskDeviceProcess taskDeviceProcess = null;
            if (obj instanceof ProTaskDeviceProcess){
                taskDeviceProcess = (ProTaskDeviceProcess) obj;
                String error = proTaskService.updateFromProTaskDeviceProcess(taskDeviceProcess);
                if (error != null){
                    return apiLog.fail(error);
                }
            }else {
                return apiLog.fail((String) obj);
            }

            RecLnspectionRecord recLnspectionRecord = new RecLnspectionRecord();
            recLnspectionRecord.setTaskDeviceProcessRecordId(taskDeviceProcess.getRecordId());
            recLnspectionRecord = recLnspectionRecordService.getOne(new QueryWrapper<RecLnspectionRecord>(recLnspectionRecord));
            return apiLog.ok(recLnspectionRecord);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 修改创建生产关联（排产任务，生产设备，工序）
     */
    @PreAuthorize("@ss.hasPermi('pro:proTaskDeviceProcess:edit')")
    @Log(title = "创建生产关联（排产任务，生产设备，工序）", businessType = BusinessType.UPDATE)
    @PutMapping(value = "edit")
    public Result<String> edit(@RequestBody ProTaskDeviceProcess proTaskDeviceProcess,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改创建生产关联（排产任务，生产设备，工序）",req,proTaskDeviceProcess);
        try {

            //获取设备
            DvMachinery dvMachinery = dvMachineryService.getById(proTaskDeviceProcess.getDeviceId());
            if (dvMachinery == null){
                return apiLog.fail("设备不存在");
            }

            //获取设备
            ProRouteProcess process = proRouteProcessService.getById(proTaskDeviceProcess.getProcessId());
            if (process == null){
                return apiLog.fail("工艺项不存在");
            }

            //获取任务
            ProTask task = proTaskService.getById(proTaskDeviceProcess.getTaskId());
            if (task == null){
                return apiLog.fail("任务不存在");
            }

            proTaskDeviceProcess.setProcessName(process.getProcessName()+":"+process.getGroupNum()+":"+proTaskDeviceProcess.getWorkType());
            proTaskDeviceProcess.setParamJson(process.getParamJson());

            proTaskDeviceProcess.setTaskName(task.getTaskName());
            proTaskDeviceProcess.setBatchNo(task.getBatchNo());

            proTaskDeviceProcess.setDeviceName(dvMachinery.getMachineryName());
            proTaskDeviceProcess.setWattHourMeter(dvMachinery.getWattHourMeter());
            proTaskDeviceProcess.setThermometer(dvMachinery.getThermometer());
            proTaskDeviceProcess.setWarmHumid(dvMachinery.getWarmHumid());

            proTaskDeviceProcessService.update(proTaskDeviceProcess);
            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 删除创建生产关联（排产任务，生产设备，工序）
     */
    @PreAuthorize("@ss.hasPermi('pro:proTaskDeviceProcess:remove')")
    @Log(title = "创建生产关联（排产任务，生产设备，工序）", businessType = BusinessType.DELETE)
	@DeleteMapping("/{recorids}")
    public Result<String> remove(@PathVariable Long[] recorids,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除创建生产关联（排产任务，生产设备，工序）",req,null);
        try {
            proTaskDeviceProcessService.delete(recorids);
            return apiLog.ok("删除成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }

    }
}
